package tech.aistar.prj.controller;

import tech.aistar.prj.model.pojo.User;
import tech.aistar.prj.service.IUserService;
import tech.aistar.prj.service.impl.UserServiceImpl;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 本类用来演示: 控制层 - 负责接受页面的数据 - > service层
 *
 * service层调用Mapper层
 * controller层调用service层
 *
 * @author: success
 * @date: 2022/3/22 8:50 上午
 */
@WebServlet(urlPatterns = "/user/*")
public class UserLoginController extends HttpServlet {
    //声明一个service对象
    //经过了单元测试了,100%是Ok的
    private IUserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取pathInfo
        String pathInfo = req.getPathInfo();
        switch (pathInfo){
            //登录功能
            case "/login":
                //所有的请求的信息都会被封装到req对象中
                //根据控件的name属性的值来接受数据
                String username = req.getParameter("username");
                String password = req.getParameter("password");

                //登录
                //user如果查询成功 - db表中的行记录
                User user = userService.login(username);
                //判断user是否为null
                if(user!=null){
                    //继续判断密码
                    if(user.getPassword().equals(password)){
                        //System.out.println("登录成功!");

                        //TODO... 首页 - 将登录成功之后的用户信息存储到session
                        HttpSession session = req.getSession();
                        session.setAttribute("user",user);

                        resp.sendRedirect("/st/video/index");
                    }else{
                        resp.sendRedirect("/st/user/loginView?error=1");
                        //System.out.println("sorry,密码错误!");
                    }
                }else{
                    resp.sendRedirect("/st/user/loginView?error=0");
                    //System.out.println("用户不存在!");
                }
                break;
            //安全退出功能
            case "/exit":
                //1. 清空session中的数据 - 但是这个session还在
                //req.getSession().invalidate();
                req.getSession().removeAttribute("user");
                //2. 重定向到登录界面
                resp.sendRedirect("/st/nav/loginView");
                break;
        }

    }
}
